package xiang.weiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xiang.weiyu.common.BaseContext;
import xiang.weiyu.common.R;
import xiang.weiyu.pojo.ShoppingCart;
import xiang.weiyu.service.ShoppingCartService;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService sService;

    /**
     * 添加到购物车
     *
     * @param shoppingCart
     * @return R<String>
     */
    @PostMapping("/add")
    public R<String> addShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        sService.insertShoppingCart(shoppingCart);
        return R.success("添加购物车成功");
    }

    /**
     * 清空购物车
     *
     * @return R<String>
     */
    @DeleteMapping("/clean")
    public R<String> cleanShoppingCart() {
        //从线程副本中获取用户登录ID
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        sService.remove(qw);
        return R.success("清空购物车成功");
    }

    /**
     * 减少购物车内单个套餐/菜品
     *
     * @param shoppingCart
     * @return R<List < ShoppingCart>>
     */
    @PostMapping("/sub")
    public R<List<ShoppingCart>> deleteShoppingCart(@RequestBody ShoppingCart shoppingCart) {
        //从线程副本中获取用户登录ID
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userId);
        //套餐不为空,说明添加到购物车的是套餐,反之是菜品
        if (shoppingCart.getSetmealId() != null) {
            qw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        } else {
            qw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }
        ShoppingCart one = sService.getOne(qw);
        //number > 1有多份数字-1 反之最后一份,直接删除
        if (one.getNumber() > 1) {
            one.setNumber(one.getNumber() - 1);
            sService.updateById(one);
        } else {
            sService.removeById(one);
        }
        //调用查询方法,返回数据
        R<List<ShoppingCart>> list = getList();
        return list;
    }

    /**
     * 查询购物车
     *
     * @return R<List < ShoppingCart>>
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> getList() {
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> list = sService.list(qw);
        return R.success(list);
    }
}
